/**
 * @file 
 * Implements Texture subsystem
 */
#include <assert.h>
#include <malloc.h>
#include <sys/stat.h>

#include "c_Engine.h"
#include "c_Texture.h"

/**
 * Create a texture object from the supplied memory buffer
 *
 * @param  Buffer Buffer containing image from which to create texture
 * @retval c_Texture object or 0
 */
wiigi::c_Texture* wiigi::c_Engine::createTexture( const unsigned char Buffer[] )
{
   c_Texture* Texture;
   Texture = new c_Texture();
   assert( 0 != Texture );
   if( 0 != Texture )
   {
      e_Status Status;
      Status = Texture->createFromBuffer( Buffer );
      if( d_StatusOK != Status )
      {
         delete Texture;
         Texture = 0;                  
      }
      
   }
   
   return Texture;
}

/**
 * Creates a texture from the supplied file
 * 
 * @param FileName Image file from which to create texture
 * @retval c_Texture object or 0 
 */
wiigi::c_Texture* wiigi::c_Engine::loadTexture( const char* FileName )
{  
   printf("c_Engine::loadTexture(): Name=%s\n", FileName );
    
   c_Texture* Texture;
   Texture = 0;
   
   struct stat FileStat;
   int RetCode;
   RetCode = stat( FileName, &FileStat );
   if( 0 == RetCode )
   {
      u8* Buffer;
      Buffer = new u8[ FileStat.st_size ];
      if( 0 != Buffer )
      {
         FILE* fp;
         fp = fopen( FileName, "rb" );
         if( 0 != fp )
         {
            int Bytes;
            Bytes = fread( Buffer, 1, FileStat.st_size, fp );
            if( FileStat.st_size == Bytes )
            {
               Texture = createTexture( Buffer );
            }
         
            fclose( fp );
            fp = 0;
         }
         
         delete Buffer;
         Buffer = 0;
      }
      
   }
   return Texture;
}
